package web

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"regexp"
)

type Context struct {
	Req  *http.Request
	Resp http.ResponseWriter

	RespStatusCode int
	RespData       []byte

	pathVal string
	regEx   string
}

func (c *Context) GetPathVal() (string, error) {
	if c.regEx == "" {
		return c.pathVal, nil
	}

	fmt.Println("reg:", c.regEx)
	ok, err := regexp.MatchString(c.regEx, c.pathVal)
	if err != nil {
		return "", errors.New("正则表达式有问题")
	}

	if !ok {
		return "", errors.New("参数无法匹配正则表达式")
	}

	return c.pathVal, nil

}

func (c *Context) BindJSON(val any) error {
	if c.Req.Body == nil {
		return errors.New("body is nil")
	}

	decoder := json.NewDecoder(c.Req.Body)
	decoder.DisallowUnknownFields()
	return decoder.Decode(val)

}

func (c *Context) RespJSONOK(val any) error {
	return c.RespJSON(http.StatusOK, val)
}

func (c *Context) RespJSON(code int, val any) error {
	bs, err := json.Marshal(val)
	if err != nil {
		return err
	}
	c.RespStatusCode = code
	c.RespData = bs

	//json.Marshal(c)
	//c.Resp.Write([]byte(c))
	c.Resp.WriteHeader(code)
	c.Resp.Write(c.RespData)
	return nil
}
